<template>
  <el-dialog v-model="dialogVisible" width="80vw" :title="dramaTitle" alignCenter draggable appendToBody destroyOnClose lockScroll :closeOnClickModal="false">
    <div style="min-height: 44vh">
      <base-skeleton v-if="pageLoad.loadState === true" style="width: 100%; height: 100%; min-height: 420px; padding: 0 20px"></base-skeleton>
      <template v-else-if="pageLoad.loadState === false">
        <div>
          <el-descriptions title="发布信息" :column="3" border style="padding-bottom: 18px">
            <template #extra>
              <!-- v-if="!dramaPushRecord.playletId" -->
              <el-button key="el-button-1" type="primary" :icon="IconPlus" :loading="createBtnLoading" @click="createDramaHandler">创建短剧</el-button>
              <el-button type="primary" :loading="syncBtnLoading" @click="syncVideoStatusHandler">
                <span style="margin-right: 6px">从{{ platformName }}平台更新剧集状态</span>
                <el-tooltip content="如更新下面某一集后上传状态会变为上传中,等一会状态没变为上传完成就可以手动同步一下状态" placement="top">
                  <icon-ep-question-filled></icon-ep-question-filled>
                </el-tooltip>
              </el-button>
              <el-button key="el-button-3" type="primary" :loading="syncDramaBtnLoading" @click="syncDramaHandler">
                <span style="margin-right: 6px">同步短剧基础信息到{{ platformName }}平台</span>
                <el-tooltip content="在短剧列表中修改了短剧信息修改后，需要在这里同步到对应小程序平台" placement="top">
                  <icon-ep-question-filled></icon-ep-question-filled>
                </el-tooltip>
              </el-button>
<!--              <el-button v-if="platformName == '微信'" key="el-button-3" type="primary" :loading="syncDramaBtnLoading" @click="syncDramaRealization">-->
<!--                <span style="margin-right: 6px">短剧变现</span>-->
<!--                <el-tooltip content="短剧变现" placement="top">-->
<!--                  <icon-ep-question-filled></icon-ep-question-filled>-->
<!--                </el-tooltip>-->
<!--              </el-button>-->
              <el-button v-if="platform !== 2" key="el-button-2" type="primary" :loading="syncThirdEpisodeBtnLoading" @click="syncThirdEpisodeHandler">
                <span style="margin-right: 6px">同步所有剧集到{{ platformName }}平台</span>
                <el-tooltip content="在更新了某几集剧集后等审核完成后需要,把剧集同步一下,用于把更新的剧集关联到剧目下" placement="top">
                  <icon-ep-question-filled></icon-ep-question-filled>
                </el-tooltip>
              </el-button>
              <el-button v-if="platform !== 3" key="el-button-2" type="success" :loading="auditBtnLoading" @click="submitDramaVerifyHandler">
                提交审核
              </el-button>
            </template>
            <el-descriptions-item label="发布平台">
              {{ platformName }}
            </el-descriptions-item>
            <el-descriptions-item label="发布时间" minWidth="110px">
              {{ dramaPushRecord.pushTime }}
            </el-descriptions-item>
            <el-descriptions-item label="审核状态" minWidth="110px">
              <span :style="aduitStatusStyle[auidtStatus.find((v) => v.value === dramaPushRecord.verifyStatus)?.value || 0]">
                {{ auidtStatus.find((v) => v.value === dramaPushRecord.verifyStatus)?.label }}
              </span>
            </el-descriptions-item>
            <el-descriptions-item label="发布版本号" minWidth="130px">
              {{ dramaPushRecord.version }}
            </el-descriptions-item>
            <el-descriptions-item label="第三方短剧ID">
              {{ dramaPushRecord.playletId }}
            </el-descriptions-item>
            <el-descriptions-item label="能力">
              {{ dramaPushRecord.scope }}
            </el-descriptions-item>
            <el-descriptions-item v-if="dramaPushRecord.dramaFailReasonList!.length > 0" label="剧目审核结果" :span="3">
              <div v-for="(item, index) in dramaPushRecord.dramaFailReasonList" :key="index">
                <span>{{ item }}</span>
              </div>
            </el-descriptions-item>
            <el-descriptions-item v-if="dramaPushRecord.episodeFailReasonList!.length > 0" key="el-descriptions-item-2" label="剧集审核结果" :span="3">
              <div v-for="(item, index) in dramaPushRecord.episodeFailReasonList" :key="index">
                <span>{{ item }}</span>
              </div>
            </el-descriptions-item>
          </el-descriptions>
          <div>
            <el-divider>短剧剧集列表</el-divider>
          </div>
          <el-scrollbar max-height="40vh">
            <el-button key="el-button-update-all" type="primary" :loading="updateAllEpisodesBtnLoading" @click="updateAllEpisodesHandler">
              一键更新剧集
              <el-tooltip content="一次性更新所有剧集视频" placement="top">
                <icon-ep-question-filled></icon-ep-question-filled>
              </el-tooltip>
            </el-button>
            <div class="slick-list-box" :style="{ '--img-width': imgwidth, '--img-height': imgHeight }">
              <div v-for="(item, index) in dramaPushRecord.dramaEpisodePushRecordDetailDTOList" :key="index" class="list-item">
                <div class="left-box">
                  <div class="image-box">
                    <base-image class="img" :src="item.episodeCover!" :previewSrcList="[item.episodeCover!]"></base-image>
                  </div>
                  <span style="display: flex; flex-direction: column; align-items: flex-start; justify-content: space-between">
                    <span>剧集标题: {{ item.episodeTitle || `第${index + 1}集` }}</span>
                    <div style="font-size: 12px; color: var(--el-text-color-secondary)">
                      <span>上传状态:</span>
                      <span :class="{ 'fail': item.pushStatus === 3 }">{{ statusMap[item.pushStatus!]?.upLabel }}</span>
                    </div>
                    <div style="font-size: 12px; color: var(--el-text-color-secondary)">
                      <span>审核状态:</span>
                      <span :class="{ 'fail': item.verifyStatus === 3 }">{{ statusMap[item.verifyStatus!]?.auditLabel }}</span>
                    </div>
                    <div style="display: flex; flex-direction: row; align-items: center; justify-content: space-between">
                      <el-button :loading="item.recordLoading" size="small" type="primary" title="更新剧集视频" @click="updateEpisodeVideoHandler(item)">
                        更新
                      </el-button>
                    </div>
                  </span>
                </div>
              </div>
            </div>
          </el-scrollbar>
        </div>
      </template>
      <base-empty
        v-else
        style="height: 100%"
        :description="pageLoad.description || ''"
        :imageSize="240"
        :loadState="pageLoad.loadState"
        :pageLoadButton="[{ text: '重新加载', callBack: getRecordDetails }]"
      ></base-empty>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
  import IconPlus from '~icons/ep/plus';
  import {
    type DramaEpisodePushRecordDetailList,
    type DramaPushRecordResponse,
    type PushPlatform,
    createDrama,
    dramaPublishDetails,
    submitDramaVerify,
    syncDramaRealizationMoney,
    syncThirdDramaInfo,
    syncThirdEpisode,
    syncVideoStatus,
    updateEpisodeVideo,
    updateOneClickEpisodeVideo,
  } from '@/api/drama-management';
  import { statusMap } from '../publish-util';

  type $ShowData = {
    dramaId: number;
    dramaTitle: string;
    platform: PushPlatform;
  };
  const imgwidth = '45px';
  const imgHeight = '80px';

  const dramaPushRecord = ref<DramaPushRecordResponse>({});
  const dramaId = ref(-1);
  const dramaTitle = ref('');
  const platform = ref<PushPlatform>(1);
  const dialogVisible = ref(false);
  const syncBtnLoading = ref(false);
  const createBtnLoading = ref(false);
  const auditBtnLoading = ref(false);
  const syncDramaBtnLoading = ref(false);
  const syncDramaRealizationLoading = ref(false);
  const syncThirdEpisodeBtnLoading = ref(false);
  const updateAllEpisodesBtnLoading = ref(false);
  const pageLoad = shallowReactive<$PageLoad>({ loadState: true, description: '' });

  const platformName = computed(() => {
    return dramaPushRecord.value.pushPlatform === 1
      ? '抖音'
      : dramaPushRecord.value.pushPlatform === 2
        ? '快手'
        : dramaPushRecord.value.pushPlatform === 3
          ? '微信'
          : '';
  });

  const auidtStatus = [
    { label: '待提审', value: 0 },
    { label: '已提审', value: 1 },
    { label: '审核通过', value: 2 },
    { label: '审核拒绝', value: 3 },
    { label: '审核中', value: 4 },
    { label: '最终失败', value: 5 },
  ];

  const aduitStatusStyle: Record<number, string> = {
    0: 'color:var(--el-color-primary)',
    1: 'color:var(--el-color-primary)',
    2: 'color:var(--el-color-success)',
    3: 'color:var(--el-color-danger)',
    4: 'color:var(--el-color-warning)',
    5: 'color:var(--el-color-danger)',
  };

  /**
   * 显示
   */
  function show(data: $ShowData) {
    dialogVisible.value = true;
    dramaId.value = data.dramaId;
    dramaTitle.value = data.dramaTitle;
    platform.value = data.platform;
    getRecordDetails();
  }

  /**
   * 获取详情
   */
  async function getRecordDetails() {
    try {
      pageLoad.loadState = true;
      const res = await dramaPublishDetails({
        dramaId: dramaId.value!,
        pushPlatform: platform.value,
      });

      res.data.episodeFailReasonList = [];
      res.data.dramaEpisodePushRecordDetailDTOList?.forEach((item) => {
        if ((item.verifyStatus === 3 || item.verifyStatus === 5) && item.failReason) {
          res.data.episodeFailReasonList?.push(`${item.episodeTitle}: ${item.failReason}`);
        }
      });

      res.data.dramaFailReasonList = [];
      if (res.data.failReason) {
        res.data.failReason = res.data.failReason ? res.data.failReason.replace('：\n示例：', '：\n') : '';
        res.data.dramaFailReasonList = res.data.failReason.split('\n');
      }
      dramaPushRecord.value = res.data;
      pageLoad.loadState = false;
    } catch (error) {
      pageLoad.loadState = 'err';
      pageLoad.description = String((error as Record<string, unknown>).msg || '') || '获取数据失败';
    }
  }

  /** 同步视频状态 */
  async function syncVideoStatusHandler() {
    await ElMessageBox.confirm(`是否从${platformName.value}平台更新剧集状态`, {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    });
    try {
      syncBtnLoading.value = true;
      const data = await syncVideoStatus({ dramaId: dramaId.value });
      data.code === 200 && ElToast.success(data.msg || '同步成功');
      syncBtnLoading.value = false;
    } catch (error) {
      syncBtnLoading.value = false;
      ElToast.error(error.msg || '同步失败，-BD003');
    }
  }

  /** 更新剧集视频 */
  async function updateEpisodeVideoHandler(item: DramaEpisodePushRecordDetailList) {
    try {
      item.recordLoading = true;
      const data = await updateEpisodeVideo({ episodeId: item.episodeId!, episodePushId: item.episodePushId! });
      data.code === 200 && ElToast.success(data.msg || '更新剧集视频成功');
      item.recordLoading = false;
    } catch (error) {
      item.recordLoading = false;
      ElToast.error(error.msg || '更新剧集视频失败，-BD003');
    }
  }

  /** 创建短剧 */
  async function createDramaHandler() {
    try {
      createBtnLoading.value = true;
      const data = await createDrama({ dramaPushId: dramaPushRecord.value.dramaPushId! });
      data.code === 200 && ElToast.success(data.msg || '创建成功');
      createBtnLoading.value = false;
    } catch (error) {
      createBtnLoading.value = false;
      ElToast.error(error.msg || '创建失败，-BD003');
    }
  }

  /** 提交审核 */
  function submitDramaVerifyHandler() {
    ElMessageBox.confirm(`提交审核前, 请确认已经同步剧目并且已经上传剧集到${platformName.value}?`, '温馨提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      draggable: true,
    })
      .then(async () => {
        try {
          auditBtnLoading.value = true;
          const data = await submitDramaVerify({ dramaPushId: dramaPushRecord.value.dramaPushId! });
          data.code === 200 && ElToast.success(data.msg || '提交成功');
          auditBtnLoading.value = false;
        } catch (error) {
          auditBtnLoading.value = false;
          ElToast.error(error.msg || '提交失败，-BD003');
        }
      })
      .catch(() => {
        console.log('取消');
      });
  }

  /** 同步剧目 */
  async function syncDramaHandler() {
    await ElMessageBox.confirm(`是否同步短剧基础信息到${platformName.value}平台`, {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    });
    try {
      syncDramaBtnLoading.value = true;
      const data = await syncThirdDramaInfo({ dramaPushId: dramaPushRecord.value.dramaPushId! });
      data.code === 200 && ElToast.success(data.msg || '同步成功');
      syncDramaBtnLoading.value = false;
    } catch (error) {
      syncDramaBtnLoading.value = false;
      ElToast.error(error.msg || '同步失败，-BD003');
    }
  }

  /** 同步剧集 */
  async function syncThirdEpisodeHandler() {
    await ElMessageBox.confirm(`是否同步所有剧集到${platformName.value}平台`, {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    });
    try {
      syncThirdEpisodeBtnLoading.value = true;
      const data = await syncThirdEpisode({ dramaPushId: dramaPushRecord.value.dramaPushId! });
      data.code === 200 && ElToast.success(data.msg || '同步成功');
      syncThirdEpisodeBtnLoading.value = false;
    } catch (error) {
      syncThirdEpisodeBtnLoading.value = false;
      ElToast.error(error.msg || '同步失败，-BD003');
    }
  }

  async function syncDramaRealization() {
    await ElMessageBox.confirm(`是否变现`, {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    });
    try {
      syncDramaRealizationLoading.value = true;
      const data = await syncDramaRealizationMoney({ dramaPushId: dramaPushRecord.value.dramaPushId! });
      data.code === 200 && ElToast.success(data.msg || '变现成功');
      syncDramaRealizationLoading.value = false;
    } catch (error) {
      syncDramaRealizationLoading.value = false;
      ElToast.error(error.msg || '变现失败，-BD003');
    }
  }

  /** 一键更新剧集 */
  async function updateAllEpisodesHandler() {
    await ElMessageBox.confirm('是否确认更新', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    });
    try {
      updateAllEpisodesBtnLoading.value = true;
      if (!dramaPushRecord.value.dramaPushId) {
        ElToast.warning('没有可更新的剧集');
        return;
      }
      const data = await updateOneClickEpisodeVideo({
        dramaPushId: dramaPushRecord.value.dramaPushId!,
      });
      data.code === 200 && ElToast.success(data.msg || '一键更新剧集成功');
    } catch (error) {
      ElToast.error(error.msg || '一键更新剧集失败，-BD003');
    } finally {
      updateAllEpisodesBtnLoading.value = false;
    }
  }

  /**
   * 隐藏
   */
  function hide() {
    dialogVisible.value = false;
  }

  defineExpose({ show, hide });
</script>

<style lang="scss" scoped>
  .form-item {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  }

  .list-item {
    box-sizing: border-box;
    display: flex;
    flex-flow: row nowrap;
    align-items: stretch;
    justify-content: space-between;
    padding: 15px;
    background: var(--el-fill-color);
    border-radius: 4px;

    .left-box {
      display: flex;
      flex-flow: row nowrap;
      align-items: stretch;
      justify-content: space-between;
    }
  }

  .image-box {
    padding-right: 15px;

    .img {
      width: var(--img-width);
      height: var(--img-height);
      border-radius: 5px;
    }
  }

  .slick-list-box {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(210px, 1fr));
    gap: 12px;
    margin-top: 10px;
  }

  .slick-list-box ::-webkit-scrollbar {
    width: 8px;
  }

  .slick-list-box ::-webkit-scrollbar-thumb {
    background: #e2e2e2;
    border-radius: 8px;
  }
  // 鼠标移入样式
  .slick-list-box ::-webkit-scrollbar-thumb:hover {
    background: #9e9e9e;
  }

  .slick-list-box ::-webkit-scrollbar-track {
    background: var(--el-dialog-bg-color);
    border-radius: 8px;
  }

  .fail {
    color: var(--el-color-danger);
  }
</style>
